package com.crrc.yzt.demo.activity

import android.os.Bundle
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.crrc.yzt.demo.blue.R
import com.crrc.yzt.demo.base.BaseActivity
import com.crrc.yzt.demo.blue.databinding.ActivityCarHomeBinding
import com.crrc.yzt.demo.fragment.AnalyseFragment
import com.crrc.yzt.demo.fragment.CarHomeFragment
import com.crrc.yzt.demo.fragment.EnergyFragment
import com.crrc.yzt.demo.fragment.ExtraFragment
import com.crrc.yzt.demo.fragment.MoreFragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class CarHomeActivity : BaseActivity() {



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityCarHomeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.apply {

            viewPager.adapter = CarHomeAdapter(supportFragmentManager,lifecycle)

            viewPager.setUpWithBottomNavigation(bottomNavigationView)
        }

       

    }





}



private const val MENU_ORDER_MASK = 0x0000ffff

fun ViewPager2.setUpWithBottomNavigation(bottomNavigationView: BottomNavigationView) {
    registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            bottomNavigationView.menu.also {
                if (it.size() > position) {
                    it[position].isChecked = true
                }
            }
        }
    })
    bottomNavigationView.setOnItemSelectedListener {
        setCurrentItem(it.order and MENU_ORDER_MASK, false)
        true
    }
}


private class CarHomeAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private val weekList = mutableListOf<Fragment>()

    init {
        weekList.add(CarHomeFragment())
        weekList.add(AnalyseFragment())
        weekList.add(ExtraFragment())
        weekList.add(MoreFragment())
    }




    override fun getItemCount(): Int {
        return weekList.size
    }

    override fun createFragment(position: Int): Fragment {
        return weekList[position]
    }

}